import fs from 'fs';
import http from 'http';
import url from 'url';
import path from 'path';
import querystring from 'querystring';
import publicfile from './file';
import register from './register'
import login from './login';
let server =http.createServer((req,res)=>{
    let result =publicfile(req,res)
    if(result){
        return
    }
    if(req.path==='/zhu'&&req.method==='POST'){
        register(req,res)
        return true;
    }
    if(req.path==='/deng'&&req.method==="POST"){
        login(req,res)
    }
    if(req.path==='/prolist'){
        if(req.method==='GET'){
            var query=querystring.parse(url.parse(req.url).query);
            let food=JSON.parse(fs.readFileSync('./data/food.json','utf-8'))
            //解构food数据 得到想要的data
            let {resultcode,reason,result}=food[0]
            //创建一个对象把我们需要的数据创建进去
            let resObj={};
            if(query.id==='0'){
                resObj.content=result["data"][0]
            }else{
                resObj.content=result["data"].find(item=>{return item.id===query.id})
            }
            if(query.title==='1'){
                console.log(query.title)
                let titlelist =result["data"].map((item,index)=>{
                    return {title:item.title,id:item.id}
                })
                resObj.title=titlelist

               
            }
            res.writeHead(resultcode,reason,{'Content-Type':'application/json;charset=utf-8'})
            res.end(JSON.stringify(resObj))
        }
        res.writeHead(200,'ok',{'Content-Type':'application/json;charset=utf-8'})

        res.end('购物车添加成功')
    }
    if(req.path==='/ind'){
        if(req.method==='GET'){
            res.end(fs.readFileSync('./data/san.json','utf-8'))
        }
        res.writeHead(200,'ok',{'Content-Type':'application/json;charset=utf-8'})
        res.end('购物车添加成功')
    }
    if(req.path==='/content'){
       
            var da=JSON.stringify(querystring.parse(url.parse(req.url).query))
            // console.log(url.parse(req.url).query)
            // res.end()
       
        res.writeHead(200,'ok',{'Content-Type':"text/html;charset=utf-8"})
        res.end(fs.writeFileSync('./public/ind.html',JSON.stringify(JSON.parse(da).name),'utf-8'))
    }
    // res.writeHead(301,'ok',{'Content-Type':'text/html;charset=utf-8','Location':'/404.html'})
    // res.end()
})
server.listen(4000,()=>{
    console.log('http://localhost:4000')
})